<!-- @format -->
<template>
	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">
			<el-form ref="form" :model="form" :label-width="$globalCss.formLabelWidth_default" :rules="formRules" v-loading="loading" label-position="right" class="common-form-panel-div">
				<template v-if="isOmsSystem">
					<ex_header_spiler :title="$tt('label_customer_info')"></ex_header_spiler>
					<el-row>
						<el-col>
							<el-form-item :label="$tt('label_customer', '客户')" prop="customerId" key="customerId">
								<common_customer_choose
									v-model="form.customerId"
									@changeItem="changeCustomer"
									:disabled="edit"
									style="width: 100%;"
									:currentLabel="$formatNameCode(form.customerName, form.customerCode)"
								>
								</common_customer_choose>
							</el-form-item>
						</el-col>
					</el-row>
				</template>

				<ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>

				<el-row>
					<el-col>
						<el-form-item :label="$tt('label_outbound_type')" prop="outType">
							<ex_super_input
								v-model="form.outType"
								type="select"
								enum="OmsOutboundOrderTypeEnum"
								style="width: 100%;"
								:listHandler="(list) => list.filter((it) => ['SALES_OUTBOUND', 'DESTROY_OUTBOUND'].includes(it))"
								:disabled="GET_TRACK_NUMBER_FAIL"
							/>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item :label="$tt('label_business_type', '业务类型')" prop="bizType">
							<ex_super_input :value="form.bizType" type="select" enum="BizTypeEnum" style="width: 100%;" @change="changeBizType" :disabled="GET_TRACK_NUMBER_FAIL" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col>
						<el-form-item :label="$tt('label_outbound_warehouse')" prop="warehouseId">
							<ex_super_input
								:value="form.warehouseId"
								style="width: 100%;"
								:items="WarehouseList"
								:attrs="{
									option: (e) => ({ label: $formatNameCode(e.warehouseName, e.warehouseCode), value: e['warehouseId'] }),
								}"
								type="select"
								@changeItem="changeWarehouseConfirm"
								:disabled="GET_TRACK_NUMBER_FAIL"
							/>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item :label="$tt('label_ec_platform')" prop="ecPlatform">
							<ex_super_input v-model="form.ecPlatform" type="select" enum="OmsOutboundOrderEcPlatformEnum" style="width: 100%;" :disabled="GET_TRACK_NUMBER_FAIL" />
						</el-form-item>
					</el-col>

					<el-col>
						<el-form-item :label="$tt('label_ec_platform_code')" prop="ecPlatformOrderNo" v-if="(SALES_OUTBOUND || DESTROY_OUTBOUND) && form.ecPlatform && form.ecPlatform != 'Other'">
							<ex_super_input v-model="form.ecPlatformOrderNo" :disabled="GET_TRACK_NUMBER_FAIL" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row>
					<el-col>
						<el-form-item :label="$tt('label_outbound_method')" prop="outboundMode" v-if="!DESTROY_OUTBOUND">
							<ex_select_auto v-model="form.outboundMode" type="select" enum="OutboundOrderModeEnum" style="width: 100%;" :disabled="GET_TRACK_NUMBER_FAIL" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row v-if="$loginUser.ifElse澳越">
					<el-col>
						<el-form-item :label="$tt('label_tax_code_type', '税号类型')" prop="taxNoType">
							<ex_select_auto v-model="form.taxNoType" style="width: 100%;" enum="TaxNoTypeEnum" @change="(e) => (form.taxNo = e ? form.taxNo : null)" />
						</el-form-item>
					</el-col>
					<el-col v-if="form.taxNoType">
						<el-form-item :label="$tt('label_tax_code', '税号')" prop="taxNo">
							<ex_super_input v-model="form.taxNo" style="width: 100%;" />
						</el-form-item>
					</el-col>
				</el-row>
				<!-- <el-row v-if="ALLOCATE_OUTBOUND">
        <el-col>
          <el-form-item label="Shipment ID" prop="shipmentId">
            <ex_super_input v-model="form.shipmentId" key="shipmentId" :disabled="GET_TRACK_NUMBER_FAIL" />
          </el-form-item>
        </el-col>

        <el-col>
          <el-form-item label="Reference ID" prop="referenceId">
            <ex_super_input v-model="form.referenceId" key="referenceId" :disabled="GET_TRACK_NUMBER_FAIL" />
          </el-form-item>
        </el-col>
      </el-row> -->

				<template v-if="SALES_OUTBOUND">
					<ex_header_spiler :title="$tt('label_consignee_info')"></ex_header_spiler>

					<template v-if="HOME_DELIVERY">
						<el-row>
							<el-col>
								<el-form-item :label="$t('label_quick_select_address')">
									<quick_select_customer_address
										:customerId="form.customerId"
										@command="
											(item) => {
												form.consignee = item.contacts;
												form.consigneePhone = item.contactNumber;
												form.country = item.countryCode;
												form.province = item.province;
												form.city = item.city;
												form.postcode = item.postalCode;
												form.address = item.addressDetail;
											}
										"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_person_name')" prop="consignee" :rules="requiredRule">
									<ex_super_input v-model="form.consignee" />
								</el-form-item>
							</el-col>
							<el-col>
								<el-form-item :label="$tt('label_consignee_person_phone')" prop="consigneePhone" :rules="requiredRule">
									<ex_super_input v-model="form.consigneePhone" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_person_email')" prop="email">
									<ex_super_input v-model="form.email" />
								</el-form-item>
							</el-col>

							<el-col>
								<el-form-item :label="$tt('label_consignee_company')" prop="companyName">
									<ex_super_input v-model="form.companyName" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_country')" prop="country">
									<country_select v-model="form.country" style="width: 100%;" />
								</el-form-item>
							</el-col>

							<el-col>
								<el-form-item :label="$tt('label_consignee_province')" prop="province">
									<ex_super_input v-model="form.province" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_city')" prop="city">
									<ex_super_input v-model="form.city" />
								</el-form-item>
							</el-col>

							<el-col>
								<el-form-item :label="$tt('label_consignee_postcode')" prop="postcode">
									<ex_super_input v-model="form.postcode" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_house_number')" prop="houseNumber">
									<ex_super_input v-model="form.houseNumber" />
								</el-form-item>
							</el-col>

							<el-col>
								<el-form-item :label="$tt('label_consignee_address')" prop="address">
									<ex_super_input v-model="form.address" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_address_reserve')" prop="reserveAddress">
									<ex_super_input v-model="form.reserveAddress" />
								</el-form-item>
							</el-col>
						</el-row>
					</template>
					<template v-else-if="TAKE_THEIR">
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_take_good_user_name')" prop="takeDeliveryPerson" :rules="requiredRule">
									<ex_super_input v-model="form.takeDeliveryPerson" />
								</el-form-item>
							</el-col>
							<el-col>
								<el-form-item :label="$tt('label_take_good_contact')" prop="takeDeliveryPersonPhone" :rules="requiredRule">
									<ex_super_input v-model="form.takeDeliveryPersonPhone" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_expected_take_good_date')" prop="takeDeliveryTime">
									<ex_super_input
										v-model="form.takeDeliveryTime"
										type="date-picker"
										key="takeDeliveryTime"
										:attrs="{
											type: 'datetime',
											format: 'yyyy-MM-dd HH:mm',
											'picker-options': {
												format: 'HH:mm',
											},
										}"
										style="width:100%"
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</template>
					<template v-else-if="EC_WAREHOUSE_DELIVERY">
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_ec_platform_warehouse')" prop="ecPlatformWarehouse" :rules="requiredRule">
									<!-- <ex_super_input v-model="form.ecPlatformWarehouse" /> -->
									<place_select
										v-model="form.ecPlatformWarehouseId"
										class="w_fill"
										typeEnum="ECOMMERCE_AREA"
										:checkCountry="false"
										@changeItem="
											(e) => {
												if (!e) e = { placeName: null, address: null };
												form.ecPlatformWarehouse = e.placeName;
												form.ecPlatformWarehouseAddr = e.address;
											}
										"
									/>
								</el-form-item>
							</el-col>
							<el-col>
								<el-form-item :label="$tt('label_require_delivery_time')" prop="requireDeliveryTime">
									<ex_super_input
										v-model="form.requireDeliveryTime"
										type="date-picker"
										key="takeDeliveryTime"
										:attrs="{
											type: 'datetime',
											format: 'yyyy-MM-dd HH:mm',
											'picker-options': {
												format: 'HH:mm',
											},
										}"
										style="width:100%"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_consignee_person_name')" prop="consignee">
									<ex_super_input v-model="form.consignee" />
								</el-form-item>
							</el-col>
							<el-col>
								<el-form-item :label="$tt('label_consignee_person_phone')" prop="consigneePhone">
									<ex_super_input v-model="form.consigneePhone" />
								</el-form-item>
							</el-col>
						</el-row>
					</template>
					<template v-else-if="LOGISTICS_TRANSFER">
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_transship_logistics_name')" prop="transferLogisticsName">
									<ex_super_input v-model="form.transferLogisticsName" />
								</el-form-item>
							</el-col>
							<el-col>
								<el-form-item :label="$tt('label_transship_receive_contact')" prop="transferConsigneePhone" :rules="requiredRule">
									<ex_super_input v-model="form.transferConsigneePhone" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_transship_receive_address')" prop="transferShippingAddress" :rules="requiredRule">
									<ex_super_input v-model="form.transferShippingAddress" />
								</el-form-item>
							</el-col>
						</el-row>
					</template>
				</template>

				<!-- 商品信息 -->
				<template v-if="SALES_OUTBOUND || DESTROY_OUTBOUND">
					<ex_header_spiler :title="$tt('label_sku_info')"></ex_header_spiler>

					<el-row>
						<el-col>
							<el-form-item>
								<el-button :disabled="GET_TRACK_NUMBER_FAIL" @click="clickWarehouseSkuSelect" icon="el-icon-plus">
									<!--  type="primary" -->
									{{ $tt(SkuOutbound ? 'label_add_sku' : 'label_add_box') }}
								</el-button>

								<el-checkbox :disabled="GET_TRACK_NUMBER_FAIL" style="margin-left: 40px; " v-model="form.ullageFlag" true-label="Y" false-label="N">{{
									$tt('label_is_allow_ullage_outbound')
								}}</el-checkbox>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col style="width: 100%; max-width: 1400px; ">
							<el-form-item :label="$tt(SkuOutbound ? 'label_sku_info' : 'label_box_code_info')" prop="detailList">
								<ex_super_table v-bind="skuTableOption" :data="form.detailList" ref="TableSkuList"> </ex_super_table>
							</el-form-item>
						</el-col>
					</el-row>
				</template>

				<template v-if="!DESTROY_OUTBOUND">
					<ex_header_spiler :title="$tt('label_other_info')"></ex_header_spiler>
					<template v-if="SALES_OUTBOUND">
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_sign_server')" prop="signReceipt">
									<ex_super_input v-model="form.signReceipt" type="select" enum="YesOrNoEnum" style="width: 100%;" :disabled="GET_TRACK_NUMBER_FAIL" />
								</el-form-item>
							</el-col>
						</el-row>
					</template>

					<template v-if="ALLOCATE_OUTBOUND">
						<el-row>
							<el-col>
								<el-form-item :label="$tt('label_attachment_label_server')" prop="attachmentList">
									<ex_super_input v-model="form.attachmentList" type="upload-file" :disabled="GET_TRACK_NUMBER_FAIL" />
								</el-form-item>
							</el-col>
						</el-row>
					</template>
				</template>

				<el-row>
					<el-col>
						<el-form-item :label="$tt('label_logistics', '物流产品')" prop="logisticsId" v-if="!DESTROY_OUTBOUND">
							<ex_super_input
								:value="form.logisticsId"
								style="width: 100%;"
								:items="ProductList"
								:attrs="{
									option: (e) => ({ label: $formatNameCode(e.productName, e.productCode), value: e['productId'] }),
								}"
								type="select"
								@changeItem="productChange"
								:disabled="GET_TRACK_NUMBER_FAIL"
							/>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item :label="$tt('label_remark')" prop="remark">
							<ex_super_input
								v-model="form.remark"
								type="input"
								:disabled="GET_TRACK_NUMBER_FAIL"
								:attrs="{ type: 'textarea', maxlength: 500, 'show-word-limit': true }"
								class="form_input_default-default"
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item prop="checkAgreement" v-if="DESTROY_OUTBOUND">
					<div class="flex_row_center">
						<el-checkbox v-model="form.checkAgreement">
							{{ $tt('label_has_read_and_agree') }}
						</el-checkbox>
						<el-link type="primary" @click="clickAgreement">《{{ $tt('title_destroy_outbound_agreement') }}》</el-link>
					</div>
				</el-form-item>
			</el-form>

			<warehouse_sku_select ref="warehouse_sku_select" @submitSuccess="returnWarehouseSkuSelect" />
		</div>
		<div class="page_rela_bottom_area">
			<template v-if="GET_TRACK_NUMBER_FAIL">
				<el-button type="primary" @click="submit('RetryGetTrack')">{{ $tt('label_retry_get_track') }}</el-button>
			</template>
			<template v-else>
				<el-button type="primary" @click="submit('Save')">{{ $tt('label_save_to_draft') }}</el-button>
				<el-button type="primary" @click="submit('Submit')">{{ $tt('label_submit_and_audit') }}</el-button>
			</template>

			<el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
		</div>
	</div>
</template>

<script>
const defaultItemObj = {
	skuId: null,
	skuOnlyCode: null,
	skuBarcode: null,
	skuNameCn: null,
	skuNameEn: null,
	usableQty: null,
	stockCount: null,
	skuPackage: null,
	currencyCode: null,

	skuDeclaredValue: null,
	boxCount: null,
	skuCount: null,
};
let defaultObj = {
	bizType: 'TOC',
	customerId: null,
	customerName: null,
	customerCode: null,

	taxNo: '',
	taxNoType: null,

	ullageFlag: 'N', //
	// orderNo: null,// string 	出库单号
	ecPlatformOrderNo: null, // string 	平台单号
	ecPlatform: null, // OmsOutboundOrderEcPlatformEnum 	AliExpress:AliExpress, Amazon:Amazon, B2C:B2C, eBay:eBay, Wildberries:Wildberries, Ozon:Ozon, Other:Other
	outType: 'SALES_OUTBOUND', // OmsOutboundOrderTypeEnum 	SALES_OUTBOUND:销售出库, RETURN_OUTBOUND:退仓出库, ALLOCATE_OUTBOUND:调拨出库, DESTROY_OUTBOUND:销毁出库
	outStatus: null, // OmsOutboundOrderStatusEnum 	DRAFT:草稿, WAREHOUSE_PROCESSING:仓库处理中, COMPLETE_OUTBOUND:已出库, COMPLETED:已完成, EXCEPTION:异常, INVALID:已作废
	outboundMode: 'HOME_DELIVERY',
	warehouseId: null, // long 	出库仓库id
	warehouseCode: null, // string 	仓库编码
	warehouseName: null,
	logisticsId: null, // long 	物流产品id
	logisticsCode: null, // string 	物流产品编码
	logisticsName: null, // string 	物流产品名称
	deliveryType: null, // string 	派送方式
	shipmentId: null, // string 	ShipmentID
	referenceId: null, // string 	ReferenceID
	cutoffDate: null, // long 	截单时间
	cutoffReason: null, // string 	截单原因
	remark: null, // string 	备注

	payOnDelivery: null, // YesOrNoEnum 	Y:是, N:否
	signReceipt: null, // YesOrNoEnum 	Y:是, N:否
	// trackNumber: null,// string 	跟踪号
	insuranceService: 'N', // YesOrNoEnum 	Y:是, N:否
	insuranceAmount: null, // bigdecimal 	投保金额
	county: null, // string 	收货区县
	province: null, // string 	收货省份
	city: null, // string 	收货城市
	country: null, // string 	收货国家
	address: null, // string 	收货地址
	reserveAddress: null, // string 	收货地址2
	consignee: null, // string 	收货人
	consigneePhone: null, // string 	收货人电话
	email: null, // string 	收件人邮箱
	postcode: null, // string 	邮编
	houseNumber: null, // string 	门牌号
	companyName: null, // string 	公司名称
	fbaWarehouseId: null, // long 	fba仓库id
	fbaWarehouseCode: null, // string 	fba仓库code
	// outDate: null,// long 	出库时间
	detailList: [], //array<object> 	新增或修改的订单明细
	removeDetailIds: [],
	attachmentList: [],
	removeAttachmentIds: [],

	outboundProductType: 'PRODUCT_OUTBOUND',
	ecPlatformWarehouseId: null,
	ecPlatformWarehouse: null,
	// orderId 		long 	出库单id
	// boxNumber 		string 	外包装箱条码
	// skuId 		long 	skuid
	// skuOnlyCode 		string 	sku编码
	// skuNameCn 		string 	sku中文名称
	// skuNameEn 		string 	sku英文名称
	// skuCount 		integer 	出库数量
	// stockCount 		integer 	库存数量
	// trackNumber 		string 	跟踪号
	// totalWeight 		bigdecimal 	重量
	// totalVolume 		bigdecimal 	体积
};
import country_select from '@/component/tms/country_select';

import place_select from '@/component/tms/place_select';
import warehouse_sku_select from './dialog/warehouse_sku_select';
import router_params from '@/mixin/router_params';
import quick_select_customer_address from '@/component/oms/quick_select_customer_address';
import bill_detail_info from '@/component/fms/bill_detail_info.vue';

import role_system_mixin from '@/mixin/role_system_mixin';
export default {
	mixins: [router_params, role_system_mixin],
	components: { warehouse_sku_select, place_select, country_select, quick_select_customer_address },

	data() {
		return {
			edit: false,
			WarehouseList: [],
			ProductList: [],
			// editOrgSkuIdList: [],//编辑时保留原sku列表数据，后台删除skuid需要=。=
			loading: false,
			form: _.cloneDeep(defaultObj),

			requiredRule: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

			formRules: {
				outType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				bizType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				ullageFlag: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

				warehouseId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				logisticsId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				// ecPlatform: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				// ecPlatformOrderNo: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

				// consignee: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				// consigneePhone: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				country: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				// province: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				city: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				postcode: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				address: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

				taxNo: { message: this.$tt('tip_exist_invalid_char'), pattern: this.$reg.RegPureNumberLetterSpecial, trigger: 'blur' },
				// takeDeliveryPerson: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				// takeDeliveryPersonPhone: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				checkAgreement: {
					type: 'boolean',
					validator: (r, v, cb) => {
						if (!v) {
							cb(this.$t('tip_place_has_read_and_agree_any', { any: this.$t('title_destroy_outbound_agreement') }));
						} else {
							cb();
						}
					},
				},

				detailList: { required: true, type: 'array', validator: this.skuListValidator, trigger: 'blur' },

				insuranceService: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				insuranceAmount: {
					validator: (r, v, cb) => {
						if (this.form.insuranceService == 'Y' && !_.isEmpty(v) && !this.$reg.DigitNumber(v, 2, 9)) {
							cb(this.$tt('tip_check_decimal_digit_int', { digit: 2, int: 9 }));
						} else {
							cb();
						}
					},
					trigger: 'blur',
				},
				// signReceipt: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
			},

			skuTableOption: {
				model: [
					{
						key: 'skuNameCn',
						label: 'label_sku_info',
						'min-width': 140,
						'show-overflow-tooltip': true,
					},
					// { key: 'skuBarcode', label: 'label_sku_code', 'width': 140, 'show-overflow-tooltip': true, if: () => this.SkuOutbound, },
					{
						key: 'skuOnlyCode',
						label: 'label_sku_only_code',
						width: 220,
						if: () => this.SkuOutbound,
					},
					{
						key: 'skuDeclaredValue',
						label: 'label_declared_value',
						width: 120,
						'show-overflow-tooltip': true,
						if: () => this.SkuOutbound,
						formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
					},
					{ key: 'stockUsage', label: 'label_stock_usage', width: 130, formatter: (r, c, v, i) => this.$enumShow(v, 'StockUsageEnum') },
					{ key: 'boxNo', label: 'label_box_code', 'min-width': 150, if: () => !this.SkuOutbound },
					{ key: 'usableQty', label: 'label_sku_count', width: 120, if: () => !this.SkuOutbound },
					{ key: 'usableQty', label: 'label_usable_count', width: 120, if: () => this.SkuOutbound },
					{
						key: 'skuPackage',
						label: 'label_sku_carton_spec',
						width: 120,
						if: () => this.TOB && this.SkuOutbound,
						formatter: (r, c, v) => `${v}/` + this.$tt('label_box'),
					},
					{
						key: 'boxCount',
						label: 'label_outbound_box_count',
						'min-width': 140,
						if: () => this.TOB,
						render: (h, { row }) => {
							if (this.SkuOutbound) {
								return (
									<el-input-number
										class='w_fill'
										value={row.boxCount}
										disabled={this.GET_TRACK_NUMBER_FAIL}
										step-strictly
										min={1}
										max={Math.ceil(row.usableQty / row.skuPackage)}
										onInput={(e) => this.changeBoxCount(e, row)}
									/>
								);
							} else {
								return row.boxCount;
							}
						},
					},
					{
						key: 'skuCount',
						label: 'label_outbound_count',
						'min-width': 140,
						if: () => this.SkuOutbound,
						render: (h, { row, index }) => {
							const value = row.skuCount;
							if (!this.TOB) {
								return (
									<el-input-number
										class='w_fill'
										value={value}
										disabled={this.GET_TRACK_NUMBER_FAIL}
										step-strictly
										min={1}
										max={row.usableQty}
										onChange={(e) => {
											this.$set(row, 'skuCount', e);
											this.$set(this.form.detailList, index, row);
										}}
									/>
								);
							} else {
								return row.skuCount;
							}
						},
					},

					{
						type: 'operate',
						width: 120,
						operate: [
							{
								label: 'label_remove',
								class: 'button_text_danger',
								disabled: () => this.GET_TRACK_NUMBER_FAIL,
								click: (row, i) => this.removeSku(row),
							},
						],
					},
				],
			},

			//目的仓库到产品路径
			products: [],

			intersection: [],
			intersectionIndex: 0,
		};
	},

	created() {
		this.getWarehouseList();
	},

	computed: {
		TOB() {
			return this.form.bizType == 'TOB';
		},
		SkuOutbound() {
			return this.form.outboundProductType == 'PRODUCT_OUTBOUND';
		},
		GET_TRACK_NUMBER_FAIL() {
			return this.form.outStatus == 'GET_TRACK_NUMBER_FAIL';
		},
		//判断当前产品是否支持保险
		ProductSupportInsurance() {
			const select_product = _.find(this.ProductList, (it) => it.productId == this.form.logisticsId);
			if (select_product) {
				return !!select_product.supportInsurance;
			}
			return false;
		},

		disabled_ullage() {
			return _.reduce(this.form.detailList, (sum, it) => this.$math_add(sum, it.skuCount), 0) <= 1;
		},
		SALES_OUTBOUND() {
			return this.form.outType == 'SALES_OUTBOUND';
		},
		ALLOCATE_OUTBOUND() {
			return this.form.outType == 'ALLOCATE_OUTBOUND';
		},
		DESTROY_OUTBOUND() {
			return this.form.outType == 'DESTROY_OUTBOUND';
		},

		HOME_DELIVERY() {
			return this.form.outboundMode == 'HOME_DELIVERY';
		},
		TAKE_THEIR() {
			return this.form.outboundMode == 'TAKE_THEIR';
		},
		EC_WAREHOUSE_DELIVERY() {
			return this.form.outboundMode == 'EC_WAREHOUSE_DELIVERY';
		},
		LOGISTICS_TRANSFER() {
			return this.form.outboundMode == 'LOGISTICS_TRANSFER';
		},
		Sum_Sku_DeclaredValue() {
			return _.reduce(this.form.detailList, (sum, it) => this.$math_add(sum, this.$math_mul(it.skuDeclaredValue ? it.skuDeclaredValue : 0, it.skuCount)), 0);
		},
	},
	methods: {
		clickAgreement(e) {
			e.stopPropagation();
			// this.$refs.ozon_agreement.show()
		},
		selectQuickAddress(item) {
			this.form.consignee = item.contacts;
			this.form.consigneePhone = item.contactNumber;
			this.form.country = item.countryCode;
			this.form.province = item.province;
			this.form.city = item.city;
			this.form.postcode = item.postalCode;
			this.form.address = item.addressDetail;
		},
		warehouseChange(e) {
			if (e) {
				this.form.warehouseId = e.warehouseId;
				this.form.warehouseCode = e.warehouseCode;
				this.form.warehouseName = e.warehouseName;
			} else {
				this.form.warehouseId = null;
				this.form.warehouseCode = null;
				this.form.warehouseName = null;
			}
			this.productChange(null);
		},
		productChange(e) {
			if (e) {
				this.form.logisticsId = e.productId;
				this.form.logisticsName = e.productName;
				this.form.logisticsCode = e.productCode;
			} else {
				this.form.logisticsId = null;
				this.form.logisticsName = null;
				this.form.logisticsCode = null;
			}
			this.form.insuranceService = 'N';
		},
		changeFBAWarehouse(e) {
			if (!e) e = { id: null, code: null, name: null };
			this.form.fbaWarehouseId = e.id;
			this.form.fbaWarehouseCode = e.code;
			this.form.fbaWarehouseName = e.name;
		},
		changeWarehouseConfirm(e) {
			this.confirmClearBox(() => {
				this.warehouseChange(e);
			});
		},
		changeCustomer(e) {
			if (!e) e = { customerId: null, customerName: null, customerCode: null };

			this.confirmClearBox(() => {
				this.form.customerId = e.customerId;
				this.form.customerName = e.customerName;
				this.form.customerCode = e.customerCode;
			});
		},
		checkBoxRow(it) {
			this.$set(it, 'error', {});
			let check = true;
			if (!it.skuCount) {
				this.$set(it.error, 'skuCount', 'tip_can_no_empty');
				check = false;
			}
			if (!this.$reg.PureNumber(it.skuCount)) {
				this.$set(it.error, 'skuCount', 'tip_only_positive_pure_decimal');
				check = false;
			}

			// else if (this.TOB && (Number(it.skuCount) % Number(it.skuPackage) != 0) && (Number(it.skuCount) != Number(it.usableQty))) {
			//   this.$set(it.error, 'skuCount', "tip_TOB_order_sku_count_only_cartonSpec")
			//   check = false
			// }
			return check;
		},
		skuListValidator(r, v, cb) {
			if (v.length == 0) {
				return cb(this.$tt('tip_please_add_least_one_sku'));
			}
			let check = true;
			v.forEach((it) => {
				if (!this.checkBoxRow(it)) check = false;
			});
			if (check) {
				cb();
			} else {
				cb(this.$tt('label_sku_specification_check_fail'));
			}
		},
		clickWarehouseSkuSelect() {
			if (!this.form.customerId && this.isOmsSystem) return this.$message.warning('请先选择操作客户');
			if (!this.form.warehouseId) return this.$message.warning('请先选择出库仓库');
			if (this.$refs.warehouse_sku_select) {
				this.$refs.warehouse_sku_select.show({
					bizType: this.form.bizType,
					outboundProductType: this.form.outboundProductType,
					warehouseId: this.form.warehouseId,
					warehouseName: this.form.warehouseName,
					warehouseCode: this.form.warehouseCode,
					customerId: this.form.customerId,
					customerName: this.form.customerName,
					customerCode: this.form.customerCode,
				});
			}
		},

		returnWarehouseSkuSelect(list) {
			let existkey = {};
			if (this.form.detailList && this.form.detailList.length > 0) {
				this.form.detailList.forEach((r) => {
					existkey[r.skuId + '-' + r.bizType + '-' + r.stockUsage + '-' + r.subContainerCode] = true;
				});
			}

			for (let i = 0; i < list.length; i++) {
				let r = list[i];
				r.boxNo = r.subContainerCode;
				let key = r.skuId + '-' + r.bizType + '-' + r.stockUsage + '-' + r.subContainerCode;
				if (existkey[key]) {
					continue;
				}
				existkey[key] = true;
				r['skuNameCn'] = r.skuName;
				r['skuCount'] = 1;
				r['boxCount'] = 1;
				this.form.detailList.push(r);
			}

			this.getPriorityTop(this.form.detailList);
		},

		removeSkuAll() {
			// this.form.detailList.forEach(row => {
			//   if (row.id) this.form.removeDetailIds.push(row.id)
			// })
			this.form.detailList = [];
		},
		removeSku(row) {
			let i = _.indexOf(this.form.detailList, row);
			if (i != -1) {
				// if (row.id) this.form.removeDetailIds.push(row.id)
				this.form.detailList.splice(i, 1);
			}
			this.getPriorityTop(this.form.detailList);
		},
		init_data_default(newParams) {
			this.form = _.cloneDeep(defaultObj);
			if (newParams.outType) this.form.outType = newParams.outType;
			this.edit = !!newParams.edit;
			let copy = !!newParams.copy;
			if (this.edit || copy) {
				if (newParams.id) {
					this.loading = true;
					this.$ajax({
						url: this.$url['oms/OutboundDetailById'],
						method: 'post',
						data: { id: newParams.id },
						complete: () => {
							this.loading = false;
						},
						success: (res) => {
							this.getPriorityTop(res.data.detailList);
							if (copy) {
								// const defaultItemKeys = Object.keys(defaultItemObj)
								res.data.outStatus = null;
								res.data.orderNo = null;
								res.data.platformOrderCode = null;
								res.data.detailList = res.data.detailList.map((it) => {
									return _.pick(it, [
										'boxNumber',
										'skuId',
										'skuBarcode',
										'skuOnlyCode',
										'skuNameCn',
										'skuNameEn',
										'skuCount',
										'stockCount',
										'declaredValue',
										'currencyCode',
										'skuPackage',
										'boxNo',
										'stockUsage',
										'bizType',
										'cargoPropertyId',
										'cargoPropertyCode',
										'cargoPropertyName',
									]);
								});
								res.data = _.pick(res.data, [
									'orderNo',
									'platformOrderNo',
									'ecPlatformOrderNo',
									'platformOrderCode',
									'bizType',
									'ecPlatform',
									'outType',
									'warehouseId',
									'warehouseCode',
									'warehouseName',
									'logisticsId',
									'logisticsCode',
									'logisticsName',
									'deliveryType',
									'shipmentId',
									'referenceId',
									'remark',
									'customerId',
									'customerCode',
									'customerName',
									'payOnDelivery',
									'signReceipt',
									'insuranceService',
									'ullageFlag',
									'insuranceAmount',
									'county',
									'province',
									'city',
									'country',
									'address',
									'reserveAddress',
									'consignee',
									'consigneePhone',
									'email',
									'postcode',
									'houseNumber',
									'companyName',
									'attachmentList',
									'outboundMode',
									'takeDeliveryPerson',
									'takeDeliveryPersonPhone',
									'takeDeliveryTime',
									'ecPlatformWarehouse',
									'ecPlatformWarehouseAddr',
									'requireDeliveryTime',
									'transferLogisticsName',
									'transferShippingAddress',
									'transferConsigneePhone',
									'outboundProductType',
									'taxNo',
									'taxNoType',
									'attachmentList',
									'detailList',
								]);
								if (res.data.outboundProductType == 'BOX_NO_OUTBOUND') {
									res.data.detailList = [];
								}
							}

							let obj = Object.assign({}, _.cloneDeep(defaultObj), res.data);

							// let new_data = {}
							if (obj.warehouseId && obj.detailList && obj.detailList.length > 0) {
								// new_data.warehouseId = obj.warehouseId
								// new_data.skuIds = _.join(obj.detailList.map(it => it.skuId), ',')
								// obj.detailList.forEach(it => {
								//   it.skuDeclaredValue = it.declaredValue
								//   it.usableQty = it.stockCount || 0
								//   it.boxCount = Math.ceil(Number(it.skuCount) / Number(it.skuPackage))
								// })

								// this.editOrgSkuIdList = obj.detailList.map(it => it.id)
								this.form = obj;

								//if (!this.GET_TRACK_NUMBER_FAIL && this.SkuOutbound) {
								this.alignment_sku_count();
								//}
							} else {
								obj.detailList = [];
								this.form = obj;
							}
							this.fixTabLabel();
						},
					});
				}
			}
			this.fixTabLabel();
		},
		fixTabLabel() {
			if (this.edit && !!this.form.id) {
				this.$emit('tagModifyLabel', {
					_key: 'label_name_code',
					name: this.$tt('label_edit_outbound_oder'),
					code: this.form.orderNo || '',
				});
			} else {
				this.$emit('tagModifyLabel', 'title_new_outbound_oder');
			}
		},
		alignment_sku_count() {
			this.loading = true;
			this.$ajax({
				url: this.$url['oms/queryStockSku'],
				method: 'post',
				data: {
					warehouseId: this.form.warehouseId,
					skuIds: _.join(
						this.form.detailList.map((it) => it.skuId),
						','
					),
					customerId: this.form.customerId,
				},
				complete: () => {
					this.loading = false;
				},
				success: (res) => {
					this.form.detailList.forEach((r) => {
						let skuItem = _.find(res.data.rows, (sku) => `${sku.bizType}_${sku.stockUsage}_${sku.skuId}` === `${r.bizType}_${r.stockUsage}_${r.skuId}`);
						this.$set(r, 'usableQty', skuItem && skuItem.usableQty ? skuItem.usableQty : 0);
					});
				},
			});
		},

		changeBizType(e) {
			this.confirmClearBox(() => {
				this.form.bizType = e;
				if (e == 'TOC') {
					this.form.outboundProductType = 'PRODUCT_OUTBOUND';
				} else if (e == 'TOB') {
					this.form.outboundProductType = 'BOX_NO_OUTBOUND';
				}
			});
		},
		changeOutboundProductType(e) {
			this.confirmClearBox(() => {
				this.form.outboundProductType = e;
			});
		},
		changeBoxCount(e, row) {
			if (Number.isNaN(Number(e))) return;
			this.$set(row, 'skuCount', Math.min(this.$math_mul(e, row.skuPackage), Number(row.usableQty)));
		},
		confirmClearBox(fun) {
			if (_.isEmpty(this.form.detailList)) {
				fun();
			} else {
				this.$confirm(this.$tt('tip_this_operate_will_fill_empty_sku_list'), this.$tt('label_tip'), {
					type: 'warning',
				})
					.then(() => {
						this.removeSkuAll();
						fun();
					})
					.catch(() => {});
			}
		},

		submitBeforeDealWith() {
			let data = _.cloneDeep(this.form);
			if (data.insuranceService == 'Y') {
				if (_.isEmpty(data.insuranceAmount)) data.insuranceAmount = this.Sum_Sku_DeclaredValue;
			} else {
				delete data.insuranceAmount;
			}
			data.detailList.forEach((it) => {
				it.declaredValue = it.skuDeclaredValue;
			});
			if(data.logisticsId){
				const item = _.find(this.ProductList,it=>it.productId == data.logisticsId)
				if(item){
					data.logisticsName = item.productName
					data.logisticsCode = item.productCode
				}
			}
			
			return data;
		},
		changeInitOutboundMode() {
			if (this.form.outboundMode == 'HOME_DELIVERY') {
				this.form.takeDeliveryPerson = null;
				this.form.takeDeliveryPersonPhone = null;
				this.form.takeDeliveryTime = null;

				this.form.ecPlatformWarehouseId = null;
				this.form.ecPlatformWarehouse = null;
				this.form.ecPlatformWarehouseAddr = null;
				this.form.requireDeliveryTime = null;

				this.form.transferLogisticsName = null;
				this.form.transferConsigneePhone = null;
				this.form.transferShippingAddress = null;
			} else if (this.form.outboundMode == 'TAKE_THEIR') {
				this.form.consignee = null;
				this.form.consigneePhone = null;
				this.form.email = null;
				this.form.companyName = null;
				this.form.country = null;
				this.form.province = null;
				this.form.city = null;
				this.form.postcode = null;
				this.form.houseNumber = null;
				this.form.address = null;
				this.form.reserveAddress = null;

				this.form.ecPlatformWarehouseId = null;
				this.form.ecPlatformWarehouse = null;
				this.form.ecPlatformWarehouseAddr = null;
				this.form.requireDeliveryTime = null;

				this.form.transferLogisticsName = null;
				this.form.transferConsigneePhone = null;
				this.form.transferShippingAddress = null;
			} else if (this.form.outboundMode == 'EC_WAREHOUSE_DELIVERY') {
				this.form.email = null;
				this.form.companyName = null;
				this.form.country = null;
				this.form.province = null;
				this.form.city = null;
				this.form.postcode = null;
				this.form.houseNumber = null;
				this.form.address = null;
				this.form.reserveAddress = null;

				this.form.takeDeliveryPerson = null;
				this.form.takeDeliveryPersonPhone = null;
				this.form.takeDeliveryTime = null;

				this.form.transferLogisticsName = null;
				this.form.transferConsigneePhone = null;
				this.form.transferShippingAddress = null;
			} else if (this.form.outboundMode == 'LOGISTICS_TRANSFER') {
				this.form.consignee = null;
				this.form.consigneePhone = null;
				this.form.email = null;
				this.form.companyName = null;
				this.form.country = null;
				this.form.province = null;
				this.form.city = null;
				this.form.postcode = null;
				this.form.houseNumber = null;
				this.form.address = null;
				this.form.reserveAddress = null;

				this.form.takeDeliveryPerson = null;
				this.form.takeDeliveryPersonPhone = null;
				this.form.takeDeliveryTime = null;

				this.form.ecPlatformWarehouseId = null;
				this.form.ecPlatformWarehouse = null;
				this.form.ecPlatformWarehouseAddr = null;
				this.form.requireDeliveryTime = null;
			}
		},
		submitBeforeTipShow(opEnum, data, res) {
			let h = this.$createElement;
			const h_logistics = data.logisticsId
				? h('div', { class: 'flex_row' }, [`${this.$tt('label_logistics')} : ${this.$formatNameCode(data.logisticsName, data.logisticsCode)}`])
				: null;

			let h_free_table = null;
			if (res && res.data && !_.isEmpty(res.data.feeDetails)) {
				h_free_table = h('div', [
					h('ex_super_table', {
						props: {
							data: res.data.feeDetails,
							height: 300,
							'show-summary': true,
							'summary-method': (param) => {
								const { columns, data } = param;
								const sums = [];
								columns.forEach((column, index) => {
									if (index === 1) {
										sums[index] = this.$t('label_pms_total_price');
										return;
									}
									if (column.property == 'feeAmount') {
										const values = data.map((item) => item[column.property]);
										sums[index] = this.$addUnit(
											_.reduce(values, (sum, it) => this.$math_add(sum, it), 0),
											res.data.currencyCode
										);
									} else {
										sums[index] = '-';
									}
								});

								return sums;
							},
							model: [
								{
									key: 'feeName',
									label: 'label_pms_service_cost',
									'min-width': 150,
								},
								{
									key: 'billCategory',
									label: 'label_fms_subject_formula_mode',
									'min-width': 200,
									render: (hr, { row }) => {
										return hr(bill_detail_info, {
											props: { row: row },
										});
									},
								},
								{
									key: 'feeAmount',
									label: 'label_fms_subject_expense_amount',
									'min-width': 160,
									render: (h, { row }) => this.$addUnit(row.feeAmount, res.data.currencyCode),
								},
							],
						},
					}),
					h('div', { class: 'color_warning' }, [this.$t('label_pms_outbound_free_tip', { code: res.data.currencyCode })]),
				]);
			} else {
				h_free_table = h('div', { class: 'color_warning' }, [this.$t('label_pms_outbound_free_fail_tip')]);
			}

			this.$msgbox({
				title: this.$tt('label_tip'),
				customClass: 'dialog_big',
				showCancelButton: true,
				message: h('div', [
					h('div', { class: 'flex_row' }, [`${this.$tt('label_outbound_warehouse')} : ${this.$formatNameCode(this.form.warehouseName, this.form.warehouseCode)}`]),
					h_logistics,
					h_free_table,
				]),
			})
				.then(() => {
					this.submitNet(opEnum == 'Submit' ? this.$url['oms/OutboundSaveAndSubmit'] : this.$url['oms/OutboundResubmit']);
				})
				.catch(() => {});
		},
		submitBeforeTip(opEnum) {
			let data = this.submitBeforeDealWith();
			// this.submitBeforeTipShow(opEnum, data, null);
			this.$ajax({
				url: this.$url['oms/GetOrderFeeCheck'],
				method: 'post',
				type: 'json',
				data: data,
				loading: this.$t('label_pms_loading_price'),
				fail: (res) => {
					this.submitBeforeTipShow(opEnum, data, null);
				},
				success: (res) => {
					this.submitBeforeTipShow(opEnum, data, res);
				},
			});
		},
		submit(opEnum) {
			if (this.$clickFast()) return;
			this.$refs['form'].validate((valid, obj) => {
				if (valid) {
					this.changeInitOutboundMode();
					if (opEnum == 'Submit') {
						this.submitBeforeTip(opEnum);
					} else {
						this.submitNet(opEnum == 'Save' ? this.$url['oms/OutboundSave'] : this.$url['oms/OutboundResubmit']);
					}
				} else {
					this.$message.error(this.$tt('form_validate_error'));
					return false;
				}
			});
		},
		submitNet(url) {
			let data = this.submitBeforeDealWith();

			this.$ajax({
				// url: "/oms-api/order/OutboundOrderRpc/saveAndSubmitOutboundOrder.json",
				url,
				method: 'post',
				type: 'json',
				data: data,
				loading: true,
				success: (res) => {
					this.$message.success(this.$tt('tip_submit_success'));
					this.return_emit(null, 'reload');
					this.$emitPage('standard>outbound_manage', 'reload');
					this.return_page_back();
				},
			});
		},
		getWarehouseList() {
			this.loading = true;
			this.$ajax({
				url: this.$url['fms/getLastProduct'],
				complete: () => {
					this.loading = false;
				},
				success: (res) => {
					if (res && res.data && res.data.rows) {
						let list = res.data.rows;
						list = list.filter((it) => it.endWarehouse).map((it) => it.endWarehouse);
						this.WarehouseList = _.unionBy(_.concat(...list), (it) => it.warehouseId);
					}
				},
			});
		},
		getPriorityTop(detailList) {
			this.intersection = [];
			this.intersectionIndex = 0;

			this.form.logisticsId = '';
			this.loading = true;
			this.$ajax({
				url: '/oms-api/property/OmsBaseCargoPropertyClientRpc/selectPage.json',
				data: { status: 'ENABLE', pageSize: 9999 },
				complete: () => {
					this.loading = false;
				},
				success: (res) => {
					if (res && res.data && res.data.rows) {
						// 获得交集
						this.intersection = res.data.rows.filter((x) => detailList.some((y) => y.cargoPropertyId === x.id));
						this.initProduct();
					}
				},
			});
		},
		initProduct() {
			this.loading = true;
			const length = this.intersection.length;
			let cargoPropertyId = null;

			if (length > 0) {
				cargoPropertyId = this.intersection[this.intersectionIndex] ? this.intersection[this.intersectionIndex].id : null;
			}

			this.$ajax({
				url: this.$url['fms/getLastProduct'],
				data: { cargoPropertyId },
				complete: () => {
					this.loading = false;
				},
				success: (res) => {
					if (!res.data || res.data.rows.length === 0) {
						// this.intersectionIndex++
						// if(this.intersectionIndex<=length){
						//   this.initProduct()
						// }
						this.ProductList = [];
						return;
					}
					if (res && res.data && res.data.rows) {
						this.ProductList = res.data.rows.filter((it) => it.endWarehouse && it.endWarehouse.some((w) => w.warehouseId == this.form.warehouseId));
					}
				},
			});
		},
	},
};
</script>
<style></style>
